#include <TFT_eSPI.h>
#include "ClosedCube_SHT31D.h"
#include <Wire.h>
#include <SPI.h>

#ifndef TFT_DISPOFF
#define TFT_DISPOFF 0x28
#endif

#ifndef TFT_SLPIN
#define TFT_SLPIN   0x10
#endif

#define TIME 3000
#define POWER_ADC 27//ADC引脚

TFT_eSPI tft = TFT_eSPI(135, 240); // Invoke custom library
ClosedCube_SHT31D sht3xd;

void setup()
{
  Serial.begin(115200);
  Serial.println("Start");

  adcAttachPin(POWER_ADC);//将引脚连接到ADC
  adcStart(POWER_ADC);//在连接的引脚总线上开始ADC转换
  analogReadResolution(16);//设置aliogRead返回值的分辨率

  Wire.begin();
	sht3xd.begin(0x44); // I2C address: 0x44 or 0x45
	Serial.print("Serial #");
	Serial.println(sht3xd.readSerialNumber());
	if (sht3xd.periodicStart(SHT3XD_REPEATABILITY_HIGH, SHT3XD_FREQUENCY_10HZ) != SHT3XD_NO_ERROR)
		Serial.println("[ERROR] Cannot start periodic mode");

  tft.init();
  tft.setRotation(1);
  tft.fillScreen(TFT_BLACK);
  tft.setTextSize(2);
  tft.setTextColor(TFT_YELLOW, TFT_BLACK);

  if (TFT_BL > 0) { // TFT_BL has been set in the TFT_eSPI library in the User Setup file TTGO_T_Display.h
    pinMode(TFT_BL, OUTPUT); // Set backlight pin to output mode
    digitalWrite(TFT_BL, TFT_BACKLIGHT_ON); // Turn backlight on. TFT_BACKLIGHT_ON has been set in the TFT_eSPI library in the User Setup file TTGO_T_Display.h
  }

}

void loop()
{
  SHT31D result = sht3xd.periodicFetchData();

  tft.setTextColor(TFT_RED, TFT_BLACK);
  float T = result.t;
  tft.drawString("T:", 30, 6, 1);
  tft.drawFloat(T,2, 70, 6, 1);
  tft.drawString("*C", 180, 6, 1);

  tft.setTextColor(TFT_GREEN, TFT_BLACK);
  float RH = result.rh;
  tft.drawString("RH:", 30, 36, 1);
  tft.drawFloat(RH, 2, 70, 36, 1);
  tft.drawString("%", 180, 36, 1);

  tft.setTextColor(TFT_YELLOW, TFT_BLACK);
  float power_adc = 2*((analogRead(POWER_ADC)*3.3)/65535)+0.4;
  tft.drawString("V:", 30, 63, 1);
  tft.drawFloat(power_adc,2, 70, 63, 1);
  tft.drawString("V", 180, 63, 1);

  delay(200);
  tft.fillScreen(TFT_BLACK);
}